<template>
  <view class="consultation-page">
    <!-- 聊天消息区域 -->
    <scroll-view 
      class="message-container" 
      scroll-y 
      :scroll-top="scrollTop"
      scroll-with-animation
      @scroll="onScroll"
    >
      <view 
        v-for="message in messageList" 
        :key="message.id" 
        class="message-item"
        :class="{ 'message-right': message.is_sender }"
      >
        <!-- 只显示对方的头像 -->
        <view class="avatar-container" v-if="!message.is_sender">
          <image 
            class="avatar" 
            :src="message.sender_info && message.sender_info.avatar ? message.sender_info.avatar : ''" 
            mode="aspectFill"
          />
        </view>
        
        <!-- 自己消息左侧已读/未读图标 -->
        <view 
          v-if="message.is_sender"
          class="read-status-icon"
          :class="{ unread: !message.is_read, read: message.is_read }"
        />
        
        <view class="message-content">
          <text class="message-text">{{ message.content }}</text>
          <text class="message-time">{{ formatTime(message.created_at) }}</text>
          <!-- 对方消息在下方显示已读/未读文字标识 -->
          <text 
            v-if="!message.is_sender"
            class="read-flag"
            :class="{ unread: !message.is_read, read: message.is_read }"
          >{{ message.is_read ? '已读' : '未读' }}</text>
        </view>
      </view>
      
      <!-- 底部加载更多指示器 -->
      <view class="loading-more" :class="{ active: isLoadingMore }">
        <view class="loader-spinner"></view>
      </view>
    </scroll-view>
    
    <!-- 输入区域 -->
    <view class="input-container">
      <view class="input-box">
        <textarea 
          class="message-input"
          v-model="inputMessage"
          placeholder="请输入消息..."
          :maxlength="500"
          @input="onInput"
          @confirm="sendMessage"
        />
        <button 
          class="send-button"
          :class="{ disabled: !canSend }"
          :disabled="!canSend"
          @click="sendMessage"
        >
          发送
        </button>
      </view>
    </view>
  </view>
</template>

<script>
import { identity } from '@/util/identity.js'
import { requests } from '@/util/request.js'

export default {
  name: "Consultation",
  data() {
    return {
      consultId: null,
      messageList: [],
      inputMessage: '',
      scrollTop: 0,
      isViewMode: false,
      isExpert: false,
      pollingTimer: null,
      isFetching: false,
      isSending: false,
      myOpenId: null,
      isLoadingMore: false,
      scrollHeight: 0,
      isAtBottom: false,
      lastScrollTop: 0
    };
  },
  computed: {
    canSend() {
      return this.inputMessage.trim() && !this.isViewMode;
    }
  },
  methods: {
    // 获取消息列表
    async loadMessages({ showErrorToast = true } = {}) {
      if (this.isFetching) return;
      this.isFetching = true;
      try {
        const res = await requests.request({
          url: `/consultation/messages/get/?ticket_id=${this.consultId}`,
          method: 'GET'
        });
        const list = Array.isArray(res?.data) ? res.data : (res?.data?.messages || []);
        const normalized = list.map(m => ({
          id: m.id,
          content: m.content,
          created_at: m.created_at,
          is_sender: m.sender_info?.open_id === this.myOpenId,
          is_read: !!m.is_read,
          sender_info: m.sender_info || null
        }));
        this.messageList = normalized;
        // 滚动到底部
        this.$nextTick(() => {
          this.scrollToBottom();
        });
      } catch (error) {
        console.error('获取消息列表失败:', error);
        if (showErrorToast) {
          uni.showToast({
            title: '加载错误，请重新进入咨询室',
            icon: 'none'
          });
        }
      } finally {
        this.isFetching = false;
      }
    },
    
    // 发送消息
    async sendMessage() {
      if (!this.canSend) return;
      if (this.isSending) return;
      
      const messageContent = this.inputMessage.trim();
      this.inputMessage = '';
      
      // 临时添加到消息列表
      const tempMessage = {
        id: Date.now(),
        content: messageContent,
        is_sender: true,
        created_at: new Date().toISOString()
      };
      this.messageList.push(tempMessage);
      
      // 滚动到底部
      this.$nextTick(() => {
        this.scrollToBottom();
      });
      
      try {
        this.isSending = true;
        await requests.request({
          url: '/consultation/message/send/',
          method: 'POST',
          data: { ticket_id: Number(this.consultId), content: messageContent }
        });
        // 成功后刷新一次，确保顺序与服务端一致
        await this.loadMessages({ showErrorToast: false });
      } catch (error) {
        console.error('发送消息失败:', error);
        uni.showToast({
          title: '发送失败，请重试',
          icon: 'none'
        });
        
        // 发送失败，移除临时消息
        const index = this.messageList.findIndex(msg => msg.id === tempMessage.id);
        if (index > -1) {
          this.messageList.splice(index, 1);
        }
      } finally {
        this.isSending = false;
      }
    },
    
    // 输入处理
    onInput() {
      // 可以在这里添加输入时的处理逻辑
    },
    
    // 滚动到底部
    scrollToBottom() {
      this.scrollTop = 99999;
    },
    
    // 滚动监听
    onScroll(e) {
      const { scrollTop, scrollHeight } = e.detail;
      this.scrollHeight = scrollHeight;
      
      // 判断是否在底部
      const isAtBottom = scrollTop + e.detail.scrollHeight >= scrollHeight - 10;
      this.isAtBottom = isAtBottom;
      
      // 如果在底部且向下滚动，触发刷新
      if (isAtBottom && scrollTop > this.lastScrollTop && !this.isLoadingMore && !this.isFetching) {
        this.triggerBottomRefresh();
      }
      
      this.lastScrollTop = scrollTop;
    },
    
    // 触发底部刷新
    async triggerBottomRefresh() {
      if (this.isLoadingMore || this.isFetching) return;
      
      this.isLoadingMore = true;
      try {
        // 重置Polling
        this.stopPolling();
        await this.loadMessages({ showErrorToast: true });
        this.startPolling();
      } catch (error) {
        console.error('底部刷新失败:', error);
        uni.showToast({
          title: '加载错误，请重新进入咨询室',
          icon: 'none'
        });
      } finally {
        this.isLoadingMore = false;
      }
    },
    
    // 格式化时间
    formatTime(timeString) {
      const date = new Date(timeString);
      const now = new Date();
      const diff = now - date;
      
      // 如果是今天
      if (date.toDateString() === now.toDateString()) {
        return date.toLocaleTimeString('zh-CN', { 
          hour: '2-digit', 
          minute: '2-digit' 
        });
      }
      
      // 如果是昨天
      const yesterday = new Date(now);
      yesterday.setDate(yesterday.getDate() - 1);
      if (date.toDateString() === yesterday.toDateString()) {
        return '昨天 ' + date.toLocaleTimeString('zh-CN', { 
          hour: '2-digit', 
          minute: '2-digit' 
        });
      }
      
      // 其他日期
      return date.toLocaleDateString('zh-CN') + ' ' + date.toLocaleTimeString('zh-CN', { 
        hour: '2-digit', 
        minute: '2-digit' 
      });
    },
    
    // 轮询控制
    startPolling() {
      this.stopPolling();
    this.pollingTimer = setInterval(() => {
      this.loadMessages({ showErrorToast: true }).catch(() => {
        // 统一错误提示
        uni.showToast({ title: '加载错误，请重新进入咨询室', icon: 'none' });
      });
    }, 10000);
    },
    stopPolling() {
      if (this.pollingTimer) {
        clearInterval(this.pollingTimer);
        this.pollingTimer = null;
      }
    }
  },
  
  async onLoad(options) {
    this.consultId = options.ticketId || options.id;
    this.isViewMode = options.view === 'true';
    this.isExpert = identity.isHealthTeam();
    
    // 初始加载显示loading，获取用户信息失败则提示并中止
    try {
      uni.showLoading({ title: '加载中...' });
      const u = await requests.getUserInfo();
      if (!u || !u.uid) {
        throw new Error('missing open_id');
      }
      this.myOpenId = u.uid;
      await this.loadMessages({ showErrorToast: true });
      this.startPolling();
    } catch (e) {
      console.error('初始化失败:', e);
      uni.showToast({ title: '加载错误，请重新进入咨询室', icon: 'none' });
    } finally {
      uni.hideLoading();
    }
  },
  onUnload() {
    this.stopPolling();
  },
  onHide() {
    this.stopPolling();
  }
};
</script>

<style scoped>
.consultation-page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f5f5;
}

.message-container {
  flex: 1;
  padding: 20rpx 20rpx;
  overflow-y: auto;
  overflow-x: hidden;
  box-sizing: border-box;
}

/* 调整滚动条位置，避免遮挡消息 */
.message-container::-webkit-scrollbar {
  width: 6rpx;
}

.message-container::-webkit-scrollbar-track {
  background: transparent;
  margin-right: 10rpx;
}

.message-container::-webkit-scrollbar-thumb {
  background: rgba(0, 0, 0, 0.2);
  border-radius: 3rpx;
  margin-right: 10rpx;
}

.message-container::-webkit-scrollbar-thumb:hover {
  background: rgba(0, 0, 0, 0.3);
}

/* 微信小程序滚动优化 */
.message-container {
  -webkit-overflow-scrolling: touch;
}

.message-item {
  display: flex;
  margin-bottom: 20rpx;
  align-items: flex-start;
  gap: 16rpx;
  width: 100%;
  box-sizing: border-box;
}

.message-item.message-right {
  justify-content: flex-end;
}

.message-content {
  max-width: 70%;
  background: white;
  border-radius: 16rpx;
  padding: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.message-item.message-right .message-content {
  background-color: #007bff;
  color: white;
}

.message-text {
  font-size: 28rpx;
  line-height: 1.5;
  display: block;
  margin-bottom: 8rpx;
  word-wrap: break-word;
  word-break: break-all;
}

.message-time {
  font-size: 22rpx;
  opacity: 0.7;
  display: block;
}

/* 自己消息左侧的已读/未读圆点图标 */
.read-status-icon {
  width: 16rpx;
  height: 16rpx;
  border-radius: 50%;
  margin-right: 8rpx;
  align-self: center;
  background-color: #ccc; /* 默认已读灰色 */
}
.read-status-icon.unread {
  background-color: #007bff; /* 未读蓝色 */
}
.read-status-icon.read {
  background-color: #bbb; /* 已读更浅灰 */
}

/* 对方消息下方的已读/未读文字标识 */
.read-flag {
  margin-top: 6rpx;
  font-size: 22rpx;
  display: block;
}
.read-flag.unread {
  color: #007bff; /* 未读蓝色 */
}
.read-flag.read {
  color: #999; /* 已读灰色 */
}

/* 底部加载更多指示器 */
.loading-more {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20rpx;
  height: 0;
  opacity: 0;
  transform: translateY(-20rpx);
  transition: all 0.3s ease;
  overflow: hidden;
}

.loading-more.active {
  height: 80rpx;
  opacity: 1;
  transform: translateY(0);
}

.loader-spinner {
  width: 32rpx;
  height: 32rpx;
  border: 4rpx solid #f3f3f3;
  border-top: 4rpx solid #F26A77;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.input-container {
  background: white;
  border-top: 1rpx solid #e0e0e0;
  padding: 20rpx;
}

.input-box {
  display: flex;
  align-items: flex-end;
  gap: 20rpx;
}

.message-input {
  flex: 1;
  min-height: 80rpx;
  max-height: 200rpx;
  padding: 20rpx;
  border: 2rpx solid #e0e0e0;
  border-radius: 24rpx;
  font-size: 28rpx;
  background-color: #f9f9f9;
  resize: none;
}

.message-input:focus {
  border-color: #007bff;
  background-color: white;
}

.send-button {
  width: 120rpx;
  height: 80rpx;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 24rpx;
  font-size: 28rpx;
  font-weight: bold;
}

.send-button.disabled {
  background-color: #ccc;
  color: #999;
}

.send-button:not(.disabled):active {
  background-color: #0056b3;
}

.avatar-container {
  flex-shrink: 0;
  width: 80rpx;
  height: 80rpx;
}

.avatar {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  background-color: #f0f0f0;
  border: 2rpx solid #F26A77;
}
</style>
